package com.lovo.javafxComponent;

import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.*;
import javafx.scene.paint.Paint;

/**
 * 图片组件
 * @author lenovo
 *
 */
public class LovoImage extends ImageView{
	/**图片宽度*/
	private int width;
	/**图片高度*/
	private int height;
	/**
	 * 构造方法
	 * @param url 图片URL路径
	 * @param x 组件X坐标
	 * @param y 组件Y坐标
	 * @param width 组件宽度
	 * @param height 组件高度
	 * @param container 加入容器
	 */
	public LovoImage(String url,int x,int y,int width,int height,Pane container) {
		this(url,x,y,width,height,container,false);
	}
	
	
	/**
	 * 构造方法
	 * @param url 图片URL路径
	 * @param x 组件X坐标
	 * @param y 组件Y坐标
	 * @param width 组件宽度
	 * @param height 组件高度
	 * @param container 加入容器
	 */
	public LovoImage(String url,int x,int y,int width,int height,Pane container,boolean border) {
		this.width = width;
		this.height = height;
		
		this.flushImage(url);
		this.setLayoutX(x);
		this.setLayoutY(y);
		
		BorderPane p = new BorderPane();
		p.setLayoutX(x);
		p.setLayoutY(y);
		p.setPrefSize(width, height);
		p.setCenter(this);
		
		if(border) {
			p.setBorder(this.getViewBorder());
		}
		
		container.getChildren().add(p);
	}
	
	/**
	 * 更新图片
	 * @param url 图片URL
	 */
	public void flushImage(String url) {
		if(url != null) {
			try {
				url = url.replace("\\","/");
				String path = url;

				if (url.indexOf(":") == -1 && url.indexOf("/") != -1) {
						String packageDirName = url.substring(0, url.lastIndexOf("/"));
						String pathUrl = Thread.currentThread().getContextClassLoader()
								.getResources(packageDirName).nextElement().toString();
						if(pathUrl.endsWith("/") == false){
							pathUrl += "/";
						}

						path = pathUrl + url.substring(url.lastIndexOf("/") + 1);
				}

				Image img = new Image(path, width, height, false, false);

				this.setImage(img);
			}catch(Exception e){
				e.printStackTrace();
			}
		}
	}
	
	private Border getViewBorder() {
		return  new Border(new BorderStroke(Paint.valueOf("#000"), 
				BorderStrokeStyle.SOLID, new CornerRadii(5), new BorderWidths(1)));
	}
	
}
